<?php

namespace App\Http\Controllers\Admin\Shop;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Good;
use App\Models\Shop\Mark;
use App\Models\Shop\Tag;
use App\Models\Shop\GoodGallery;

class GoodController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_shop' => 'active open',
            '_good' => 'active',
            'marks' => Mark::orderBy('sort_order', 'desc')->get(),
            'tags' => Tag::all_tags(),
            'filter_tags' => Tag::filter_tags()
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = function ($query) use ($request) {
            //按商品名称
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('name', 'like', $search);
            }

            //按分类
            if ($request->has('tag_id') and $request->tag_id != '-1') {
                $tag_id = $request->tag_id;
                $good_ids = \DB::table('good_tag')->where('tag_id', $tag_id)->pluck('good_id');
                $query->whereIn('id', $good_ids);
            }

            //按品牌
            if ($request->has('mark_id') and $request->mark_id != '-1') {
                $query->where('mark_id', $request->mark_id);
            }

            //按上架状态搜索
            if ($request->has('is_onsale') and $request->is_onsale != '-2') {
                $query->where('is_onsale', $request->is_onsale);
            }

            //按照时间搜索
            if ($request->has('created_at') and $request->created_at != '') {
                $time = explode(" ~ ", $request->input('created_at'));
                $start_time = $time[0] . ' 00:00:00'; //这里单引号前面要打一空格
                $end_time = $time[1] . ' 23:59:59';
                $query->whereBetween('created_at', [$start_time, $end_time]);
            }
        };

        $goods = Good::with('mark', 'tags')->where($where)->orderBy('is_top', 'desc')->orderBy('sort_order', 'desc')->paginate(env('pageSize'));
//        return $goods;
        return view('admin.shop.good.index', compact('goods'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.shop.good.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $good = Good::create($request->all());

        //商品相册插入相册表
        if ($request->has('imgs')) {
            foreach ($request->imgs as $img) {
                $good->good_galleries()->create(['img' => $img]);
            }
        }

        //商品所属栏目
        $good->tags()->sync($request->tag_id); //同步分类数据

        return redirect(route('shop.good.index'))->with('success', '新增商品成功~');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $good = Good::with('good_galleries', 'mark', 'tags')->find($id);

        //查出当前商品对应的分类ID
        $g_tags = $good->tags->pluck('id');
//        return $g_tags;

        return view('admin.shop.good.edit', compact('good', 'g_tags'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $good = Good::find($id);
        //先同步分类
        $good->tags()->sync($request->tag_id);

        //更新商品
        $good->update($request->all());

        //更新商品相册
        if ($request->has('imgs')) {
            foreach ($request->imgs as $img) {
                $good->good_galleries()->create(['img' => $img]);
            }
        }

        return redirect(route('shop.good.index'))->with('success', '编辑商品成功~');

    }

    public function destroy_gallery(Request $request)
    {
        GoodGallery::destroy($request->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Good::destroy($id);
        //删除商品的同时还要删除对应的商品分类表和商品相册表的数据
        if (is_array($id)) {
            \DB::table('good_tag')->whereIn('good_id', $id)->delete();
            \DB::table('good_galleries')->whereIn('good_id', $id)->delete();
        } else {
            \DB::table('good_tag')->where('good_id', $id)->delete();
            \DB::table('good_galleries')->where('good_id', $id)->delete();
        }
        return back()->with('success', '商品已成功移至回收站~');
    }


    /**
     * ajax 排序
     * @param Request $request
     */
    public function sort_order(Request $request)
    {
        $good = Good::find($request->id);
        $good->sort_order = $request->sort_order;
        $good->save();
    }


    /**
     * ajax 改变库存
     * @param Request $request
     */
    public function stock(Request $request)
    {
        $good = Good::find($request->id);
        $good->stock = $request->stock;
        $good->save();
    }


    /**
     * ajax改变属性
     * @param Request $request
     */
    public function change_attr(Request $request)
    {
        $good = Good::find($request->id);
        $attr = $request->attr;
        $good->$attr = !$good->$attr;
        $good->save();
    }


    /**
     * 多选删除
     * @param Request $request
     */
    public function delete_more(Request $request)
    {
        $checked_id = $request->checked_id;
        Good::destroy($checked_id);
    }


    /**
     * 回收站
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function trash()
    {
        view()->share([
            '_shop' => 'active open',
            '_good' => '',
            '_good_trash' => 'active'
        ]);
        $goods = Good::with('tags', 'mark')->onlyTrashed()->paginate(env('pageSize'));
//        return $goods;
        return view('admin.shop.good.trash', compact('goods'));
    }


    /**
     * 还原
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function restore($id)
    {
        Good::withTrashed()->where('id', $id)->restore();
        return back()->with('success', '还原成功');
    }

    /**
     * 永久删除
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function force_destroy($id)
    {
        Good::withTrashed()->where('id', $id)->forceDelete();
        GoodGallery::where('good_id', $id)->delete();
        return back()->with('success', '删除成功');
    }


    /**
     * 多选永久删除
     * @param Request $request
     */
    function force_destroy_checked(Request $request)
    {
        $checked_id = $request->input("checked_id");
        GoodGallery::whereIn('good_id', $checked_id)->delete();
        Good::withTrashed()->whereIn('id', $checked_id)->forceDelete();
    }


    /**
     * 多选还原
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function restore_checked(Request $request)
    {
        $checked_id = $request->input("checked_id");
        Good::withTrashed()->whereIn('id', $checked_id)->restore();
        return back()->with('success', '还原成功');
    }


}
